﻿' ******************************************************************************
' ** 
' **  Yahoo! Managed
' **  Written by Marius Häusler 2011
' **  It would be pleasant, if you contact me when you are using this code.
' **  Contact: YahooFinanceManaged@gmail.com
' **  Project Home: http://code.google.com/p/yahoo-finance-managed/
' **  
' ******************************************************************************
' **  
' **  Copyright 2011 Marius Häusler
' **  
' **  Licensed under the Apache License, Version 2.0 (the "License");
' **  you may not use this file except in compliance with the License.
' **  You may obtain a copy of the License at
' **  
' **    http://www.apache.org/licenses/LICENSE-2.0
' **  
' **  Unless required by applicable law or agreed to in writing, software
' **  distributed under the License is distributed on an "AS IS" BASIS,
' **  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
' **  See the License for the specific language governing permissions and
' **  limitations under the License.
' ** 
' ******************************************************************************


Namespace YahooManaged.Finance

    Friend Class FinanceHelper

        Public Const NameOptionSymbol As String = "symbol"
        Public Const NameOptionType As String = "type"
        Public Const NameOptionLastPrice As String = "lastPrice"
        Public Const NameOptionStrikePrice As String = "strikePrice"
        Public Const NameOptionChange As String = "change"
        Public Const NameOptionBid As String = "bid"
        Public Const NameOptionAsk As String = "ask"
        Public Const NameOptionVolume As String = "vol"
        Public Const NameOptionOpenInterest As String = "openInt"
        Public Const NameOptionChangeDir As String = "changeDir"

        Public Const NameQuoteBaseID As String = "Symbol"
        Public Const NameQuoteBaseLastTradePriceOnly As String = "LastTradePriceOnly"
        Public Const NameQuoteBaseChange As String = "Change"
        Public Const NameQuoteBaseOpen As String = "Open"
        Public Const NameQuoteBaseDaysHigh As String = "DaysHigh"
        Public Const NameQuoteBaseDaysLow As String = "DaysLow"
        Public Const NameQuoteBaseVolume As String = "Volume"
        Public Const NameQuoteBaseLastTradeDate As String = "LastTradeDate"
        Public Const NameQuoteBaseLastTradeTime As String = "LastTradeTime"

        Public Const NameHistQuoteDate As String = "Date"
        Public Const NameHistQuoteOpen As String = "Open"
        Public Const NameHistQuoteHigh As String = "High"
        Public Const NameHistQuoteLow As String = "Low"
        Public Const NameHistQuoteClose As String = "Close"
        Public Const NameHistQuoteVolume As String = "Volume"
        Public Const NameHistQuoteAdjClose As String = "AdjClose"

        Public Const NameMarketName As String = "name"
        Public Const NameIndustryID As String = "id"
        Public Const NameCompanySymbol As String = "symbol"
        Public Const NameCompanyCompanyName As String = "CompanyName"
        Public Const NameCompanyStart As String = "start"
        Public Const NameCompanyEnd As String = "end"
        Public Const NameCompanySector As String = "Sector"
        Public Const NameCompanyIndustry As String = "Industry"
        Public Const NameCompanyFullTimeEmployees As String = "FullTimeEmployees"
        Public Const NameCompanyNotAvailable As String = "NaN"

        Private mDefaultCulture As New Globalization.CultureInfo("en-US")

        Public ReadOnly Property DefaultYqlCulture() As Globalization.CultureInfo
            Get
                Return mDefaultCulture
            End Get
        End Property

        Public Function IIDsToStrings(ByVal idList As IEnumerable(Of IID)) As String()
            Dim lst As New List(Of String)
            If idList IsNot Nothing Then
                For Each id As IID In idList
                    If id IsNot Nothing AndAlso id.ID <> String.Empty Then lst.Add(id.ID)
                Next
            End If
            Return lst.ToArray
        End Function
        Public Function SectorEnumToArray(ByVal values As IEnumerable(Of Sector)) As Sector()
            Dim lst As New List(Of Sector)
            If values IsNot Nothing Then
                lst.AddRange(values)
            End If
            Return lst.ToArray
        End Function
        Public Function CleanIDfromAT(ByVal enm As IEnumerable(Of String)) As String()
            If enm IsNot Nothing Then
                Dim lst As New List(Of String)
                For Each id In enm
                    lst.Add(Me.CleanIndexID(id))
                Next
                Return lst.ToArray
            Else
                Return Nothing
            End If
        End Function
        Public Function CleanIndexID(ByVal id As String) As String
            Return id.Replace("@", "")
        End Function
        Public Function CheckPropertiesOfQuotesData(ByVal quotes As IEnumerable(Of QuoteData), ByVal properties As IEnumerable(Of QuoteProperty)) As QuoteProperty()
            Dim lstProperties As New List(Of QuoteProperty)
            If properties Is Nothing Then : Return GetAllActiveProperties(quotes)
            Else
                lstProperties.AddRange(properties)
                If lstProperties.Count = 0 Then : Return GetAllActiveProperties(quotes)
                Else : Return lstProperties.ToArray
                End If
            End If
        End Function

        Public Function GetAllActiveProperties(ByVal quotes As IEnumerable(Of QuoteData)) As QuoteProperty()
            Dim lst As New List(Of QuoteProperty)
            If quotes IsNot Nothing Then
                For Each qp As QuoteProperty In [Enum].GetValues(GetType(QuoteProperty))
                    Dim valueIsNotNull As Boolean = False
                    For Each quote As QuoteData In quotes
                        If quote(qp) IsNot Nothing Then
                            valueIsNotNull = True
                            Exit For
                        End If
                    Next
                    If valueIsNotNull Then lst.Add(qp)
                Next
            End If
            Return lst.ToArray
        End Function

        Public Function GetStringMillionFactor(ByVal s As String) As Double
            If s.EndsWith("T"c) Then : Return 1 / 1000
            ElseIf s.EndsWith("M"c) Then : Return 1
            ElseIf s.EndsWith("B"c) Then : Return 1000
            Else : Return 0
            End If
        End Function
        Public Function GetMillionValue(ByVal s As String) As Double
            Dim v As Double = 0
            Double.TryParse(s.Substring(0, s.Length - 1), Globalization.NumberStyles.Any, mDefaultCulture, v)
            Return v * Me.GetStringMillionFactor(s)
        End Function
        Public Function CleanTd(ByVal value As String) As String
            Dim sb As New List(Of Char)
            If value.Length > 0 Then
                Dim allowCopy As Boolean = True
                For i As Integer = 0 To value.Length - 1
                    If value(i) = "<"c Then : allowCopy = False
                    ElseIf value(i) = ">"c Then : allowCopy = True : Continue For
                    End If
                    If allowCopy Then sb.Add(value(i))
                Next
            End If
            Return New String(sb.ToArray).Replace("&nbsp;", "")
        End Function
        Public Function ParseToDouble(ByVal s As String) As Double
            Dim v As Double = 0
            Double.TryParse(s.Replace("%", ""), Globalization.NumberStyles.Any, mDefaultCulture, v)
            Return v
        End Function
        Public Function IsIsinValidFormatted(ByVal isin As String) As Boolean
            If isin.Length = 11 Or isin.Length = 12 Then
                If Char.IsLetter(isin(0)) And Char.IsLetter(isin(1)) Then
                    For i As Integer = 2 To 10
                        If isin(i) = String.Empty Or (Not Char.IsLetterOrDigit(isin(i))) Then Return False
                    Next
                    Return Not (isin.Length = 12 AndAlso Not Char.IsDigit(isin(11)))
                End If
            End If
            Return False
        End Function
        Public Function YCurrencyIDFromString(ByVal id As String) As Support.YCurrencyID
            Dim idStr As String = id.ToUpper
            Dim regex As New System.Text.RegularExpressions.Regex("[A-Z][A-Z][A-Z][A-Z][A-Z][A-Z]=X")
            If idStr.Length = 8 AndAlso regex.Match(idStr).Success Then
                Dim base As CurrencyInfo = Nothing
                Dim dep As CurrencyInfo = Nothing
                Dim baseStr As String = idStr.Substring(0, 3)
                Dim depStr As String = idStr.Substring(3, 3)
                For Each cur In Support.WorldMarket.DefaultCurrencies
                    If baseStr = cur.ID Then
                        base = New CurrencyInfo(cur.ID, cur.Description)
                    ElseIf depStr = cur.ID Then
                        dep = New CurrencyInfo(cur.ID, cur.Description)
                    End If
                    If base IsNot Nothing And dep IsNot Nothing Then
                        Return New Support.YCurrencyID(base, dep)
                    End If
                Next

                Return Nothing
            Else
                Return Nothing
            End If
        End Function

        Public Function GetChartImageSize(ByVal value As ChartImageSize) As String
            Return value.ToString.Substring(0, 1).ToLower
        End Function
        Public Function GetChartTimeSpan(ByVal value As ChartTimeSpan) As String
            If value = ChartTimeSpan.cMax Then : Return "my"
            Else : Return value.ToString.Replace("c", "").ToLower
            End If
        End Function
        Public Function GetChartType(ByVal value As ChartType) As String
            Return value.ToString.Substring(0, 1).ToLower
        End Function
        Public Function GetChartScale(ByVal value As ChartScale) As String
            If value = ChartScale.Arithmetic Then : Return "off"
            Else : Return "on"
            End If
        End Function
        Public Function GetMovingAverageInterval(ByVal value As MovingAverageInterval) As String
            Return value.ToString.Replace("m", "")
        End Function
        Public Function GetTechnicalIndicatorsI(ByVal value As TechnicalIndicator) As String
            Select Case value
                Case TechnicalIndicator.Bollinger_Bands : Return value.ToString.Substring(0, 1).ToLower & ","c
                Case TechnicalIndicator.Parabolic_SAR : Return value.ToString.Substring(0, 1).ToLower & ","c
                Case TechnicalIndicator.Splits : Return value.ToString.Substring(0, 1).ToLower & ","c
                Case TechnicalIndicator.Volume : Return value.ToString.Substring(0, 1).ToLower & ","c
                Case Else : Return String.Empty
            End Select
        End Function
        Public Function GetTechnicalIndicatorsII(ByVal value As TechnicalIndicator) As String
            Select Case value
                Case TechnicalIndicator.MACD : Return "m26-12-9,"
                Case TechnicalIndicator.MFI : Return "f14,"
                Case TechnicalIndicator.ROC : Return "p12,"
                Case TechnicalIndicator.RSI : Return "r14,"
                Case TechnicalIndicator.Slow_Stoch : Return "ss,"
                Case TechnicalIndicator.Fast_Stoch : Return "fs,"
                Case TechnicalIndicator.Vol : Return "v,"
                Case TechnicalIndicator.Vol_MA : Return "vm,"
                Case TechnicalIndicator.W_R : Return "w14,"
                Case Else : Return String.Empty
            End Select
        End Function

        Public Function GetHistQuotesInterval(ByVal item As HistQuotesInterval) As Char
            Select Case item
                Case HistQuotesInterval.Daily : Return "d"c
                Case HistQuotesInterval.Weekly : Return "w"c
                Case Else : Return "m"c
            End Select
        End Function

        Public Function MarketQuotesRankingTypeString(ByVal rankedBy As MarketQuoteProperty) As String
            Select Case rankedBy
                Case MarketQuoteProperty.Name : Return "coname"
                Case MarketQuoteProperty.DividendYieldPercent : Return "yie"
                Case MarketQuoteProperty.LongTermDeptToEquity : Return "qto"
                Case MarketQuoteProperty.MarketCapitalizationInMillion : Return "mkt"
                Case MarketQuoteProperty.NetProfitMarginPercent : Return "qpm"
                Case MarketQuoteProperty.OneDayPriceChangePercent : Return "pr1"
                Case MarketQuoteProperty.PriceEarningsRatio : Return "pee"
                Case MarketQuoteProperty.PriceToBookValue : Return "pri"
                Case MarketQuoteProperty.PriceToFreeCashFlow : Return "prf"
                Case MarketQuoteProperty.ReturnOnEquityPercent : Return "ttm"
                Case Else : Return String.Empty
            End Select
        End Function
        Public Function MarketQuotesRankingDirectionString(ByVal dir As System.ComponentModel.ListSortDirection) As String
            If dir = ListSortDirection.Ascending Then : Return "u"c
            Else : Return "d"c
            End If
        End Function

        Public Function CsvQuotePropertyTags(ByVal properties() As QuoteProperty) As String
            Dim symbols As New Text.StringBuilder
            If properties IsNot Nothing AndAlso properties.Length > 0 Then
                For Each qp As QuoteProperty In properties
                    Select Case qp
                        Case QuoteProperty.Ask : symbols.Append("a0")
                        Case QuoteProperty.AverageDailyVolume : symbols.Append("a2")
                        Case QuoteProperty.AskSize : symbols.Append("a5")
                        Case QuoteProperty.Bid : symbols.Append("b0")
                        Case QuoteProperty.AskRealtime : symbols.Append("b2")
                        Case QuoteProperty.BidRealtime : symbols.Append("b3")
                        Case QuoteProperty.BookValuePerShare : symbols.Append("b4")
                        Case QuoteProperty.BidSize : symbols.Append("b6")
                        Case QuoteProperty.Change_ChangeInPercent : symbols.Append("c"c)
                        Case QuoteProperty.Change : symbols.Append("c1")
                        Case QuoteProperty.Commission : symbols.Append("c3")
                        Case QuoteProperty.Currency : symbols.Append("c4")
                        Case QuoteProperty.ChangeRealtime : symbols.Append("c6")
                        Case QuoteProperty.AfterHoursChangeRealtime : symbols.Append("c8")
                        Case QuoteProperty.TrailingAnnualDividendYield : symbols.Append("d0")
                        Case QuoteProperty.LastTradeDate : symbols.Append("d1")
                        Case QuoteProperty.TradeDate : symbols.Append("d2")
                        Case QuoteProperty.DilutedEPS : symbols.Append("e0")
                        Case QuoteProperty.EPSEstimateCurrentYear : symbols.Append("e7")
                        Case QuoteProperty.EPSEstimateNextYear : symbols.Append("e8")
                        Case QuoteProperty.EPSEstimateNextQuarter : symbols.Append("e9")
                        Case QuoteProperty.TradeLinksAdditional : symbols.Append("f0")
                        Case QuoteProperty.SharesFloat : symbols.Append("f6")
                        Case QuoteProperty.DaysLow : symbols.Append("g0")
                        Case QuoteProperty.HoldingsGainPercent : symbols.Append("g1")
                        Case QuoteProperty.AnnualizedGain : symbols.Append("g3")
                        Case QuoteProperty.HoldingsGain : symbols.Append("g4")
                        Case QuoteProperty.HoldingsGainPercentRealtime : symbols.Append("g5")
                        Case QuoteProperty.HoldingsGainRealtime : symbols.Append("g6")
                        Case QuoteProperty.DaysHigh : symbols.Append("h0")
                        Case QuoteProperty.MoreInfo : symbols.Append("i"c)
                        Case QuoteProperty.OrderBookRealtime : symbols.Append("i5")
                        Case QuoteProperty.YearLow : symbols.Append("j0")
                        Case QuoteProperty.MarketCapitalization : symbols.Append("j1")
                        Case QuoteProperty.SharesOutstanding : symbols.Append("j2")
                        Case QuoteProperty.MarketCapRealtime : symbols.Append("j3")
                        Case QuoteProperty.EBITDA : symbols.Append("j4")
                        Case QuoteProperty.ChangeFromYearLow : symbols.Append("j5")
                        Case QuoteProperty.PercentChangeFromYearLow : symbols.Append("j6")
                        Case QuoteProperty.YearHigh : symbols.Append("k0")
                        Case QuoteProperty.LastTradeRealtimeWithTime : symbols.Append("k1")
                        Case QuoteProperty.ChangeInPercentRealtime : symbols.Append("k2")
                        Case QuoteProperty.LastTradeSize : symbols.Append("k3")
                        Case QuoteProperty.ChangeFromYearHigh : symbols.Append("k4")
                        Case QuoteProperty.ChangeInPercentFromYearHigh : symbols.Append("k5")
                        Case QuoteProperty.LastTradeWithTime : symbols.Append("l0")
                        Case QuoteProperty.LastTradePriceOnly : symbols.Append("l1")
                        Case QuoteProperty.HighLimit : symbols.Append("l2")
                        Case QuoteProperty.LowLimit : symbols.Append("l3")
                        Case QuoteProperty.DaysRange : symbols.Append("m"c)
                        Case QuoteProperty.DaysRangeRealtime : symbols.Append("m2")
                        Case QuoteProperty.FiftydayMovingAverage : symbols.Append("m3")
                        Case QuoteProperty.TwoHundreddayMovingAverage : symbols.Append("m4")
                        Case QuoteProperty.ChangeFromTwoHundreddayMovingAverage : symbols.Append("m5")
                        Case QuoteProperty.PercentChangeFromTwoHundreddayMovingAverage : symbols.Append("m6")
                        Case QuoteProperty.ChangeFromFiftydayMovingAverage : symbols.Append("m7")
                        Case QuoteProperty.PercentChangeFromFiftydayMovingAverage : symbols.Append("m8")
                        Case QuoteProperty.Name : symbols.Append("n0")
                        Case QuoteProperty.Notes : symbols.Append("n4")
                        Case QuoteProperty.Open : symbols.Append("o0")
                        Case QuoteProperty.PreviousClose : symbols.Append("p0")
                        Case QuoteProperty.PricePaid : symbols.Append("p1")
                        Case QuoteProperty.ChangeInPercent : symbols.Append("p2")
                        Case QuoteProperty.PriceSales : symbols.Append("p5")
                        Case QuoteProperty.PriceBook : symbols.Append("p6")
                        Case QuoteProperty.ExDividendDate : symbols.Append("q0")
                        Case QuoteProperty.PERatio : symbols.Append("r0")
                        Case QuoteProperty.DividendPayDate : symbols.Append("r1")
                        Case QuoteProperty.PERatioRealtime : symbols.Append("r2")
                        Case QuoteProperty.PEGRatio : symbols.Append("r5")
                        Case QuoteProperty.PriceEPSEstimateCurrentYear : symbols.Append("r6")
                        Case QuoteProperty.PriceEPSEstimateNextYear : symbols.Append("r7")
                        Case QuoteProperty.Symbol : symbols.Append("s0")
                        Case QuoteProperty.SharesOwned : symbols.Append("s1")
                        Case QuoteProperty.Revenue : symbols.Append("s6")
                        Case QuoteProperty.ShortRatio : symbols.Append("s7")
                        Case QuoteProperty.LastTradeTime : symbols.Append("t1")
                        Case QuoteProperty.TradeLinks : symbols.Append("t6")
                        Case QuoteProperty.TickerTrend : symbols.Append("t7")
                        Case QuoteProperty.OneyrTargetPrice : symbols.Append("t8")
                        Case QuoteProperty.Volume : symbols.Append("v0")
                        Case QuoteProperty.HoldingsValue : symbols.Append("v1")
                        Case QuoteProperty.HoldingsValueRealtime : symbols.Append("v7")
                        Case QuoteProperty.YearRange : symbols.Append("w0")
                        Case QuoteProperty.DaysValueChange : symbols.Append("w1")
                        Case QuoteProperty.DaysValueChangeRealtime : symbols.Append("w4")
                        Case QuoteProperty.StockExchange : symbols.Append("x0")
                        Case QuoteProperty.TrailingAnnualDividendYieldInPercent : symbols.Append("y0")
                    End Select
                Next
            End If
            Return symbols.ToString
        End Function
        Public Function ServerToDelimiter(ByVal server As Server) As Char
            If server = server.Australia Or _
               server = server.Canada Or _
               server = server.HongKong Or _
               server = server.India Or _
               server = server.Korea Or _
               server = server.Mexico Or _
               server = server.Singapore Or _
               server = server.UK Or _
               server = server.USA Then
                Return ","c
            Else
                Return ";"c
            End If
        End Function
        Public Function ReplaceDjiID(ByVal id As String) As String
            If id.ToUpper = "^DJI" Then : Return "INDU"
            Else : Return id
            End If
        End Function

    End Class

End Namespace
